package com.app.mingluxing.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.app.mingluxing.R;
import com.app.mingluxing.base.BaseFragment;
import com.app.mingluxing.bean.Child;
import com.app.mingluxing.bean.ChildAndWatchInforResult;
import com.app.mingluxing.bean.LocationBean;
import com.app.mingluxing.home.ChooseLocationBabyActivity;
import com.app.mingluxing.location.HistoryActivity;
import com.app.mingluxing.location.SafeAreaActivity;
import com.app.mingluxing.location.SnCodeActivity;
import com.app.mingluxing.location.WatchStatusActivity;
import com.app.mingluxing.location.WhiteListActivity;
import com.app.mingluxing.my.AddBabyActivity;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.utils.AbDateUtil;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.utils.LogUtil;
import com.app.mingluxing.widget.BatteryView;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;

import org.json.JSONException;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 定位fragment
 * Created by Administrator on 2015/7/20.
 */
public class LocationFragment extends BaseFragment implements View.OnClickListener {

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    //宝宝定位的点
    private LatLng point = null;
    private OverlayOptions option = null;
    private BitmapDescriptor mBitmap;
    private Marker marker = null;

    private MyLocationConfiguration.LocationMode mCurrentMode;
    private MyLocationListenner myListener = new MyLocationListenner();
    // 定位相关
    private LocationClient mLocClient;
    //private ViewPager vp_child;
//    //是否是第一次定位
//    private boolean isFirstLoc = true;
    private ProgressDialog settingDialog;
    private Intent mIntent;
    private ProgressDialog progressDialog;
    private TextView tv_title_name;
    //    private TextView tv_time;
    private TextView tv_title;
    private TextView tv_child_location;
    private TextView tv_watch_battery;
    private TextView tv_location_type;
    private TextView tv_status;
    private BatteryView mBatteryView;
    private ImageView iv_location_type;
    private ImageView iv_status;
//    //当前选择的孩子的数据

    private final static int LOCATION_MSG_CODE_TEN = 0x99;//定位handle message code  GSM 和 ""
    private String location_type = ""; // 定位类型,  点击导航栏
    private static final String LOCATION_TYPE_LOC = "loc";//loc 定位
    private static final String LOCATION_TYPE_GPS = "gps";//gps 定位

    //    private final static int LOCATION_MSG_CODE_THREE = 0x98;//定位handle message code GPS
//    private Child currentShowBaby;///////删删删删删删删删删删删删删删删删删删除

    public List<Child> childList = new ArrayList<>();

    //    private ExecutorService executor;
    private MapStatusUpdate u;
    private String babyName;
    private InfoWindow myInfoWindow;
    private double babyStuLat;
    private double babyStuLng;
    private RelativeLayout rl_no_baby;
    private TextView tv_add;
    private ImageView iv_left;
    private LocationBean.LocationChildInfo childInfo = null;
    private final static long LOCATION_INTERVAL_TIME = 30 * 1000;//定位间隔 30秒
    //    private String watchPhoneNum;//手表电话
//    private boolean isDelay = false; //是否需要延迟30秒发送定位请求
    private boolean firstLoc = true; //是否是第一次loc请求
    private String curPhoneNum;//当前老人的手表号码

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_location, null);

        EventBus.getDefault().register(this);

        firstLoc = true;//第一次loc 定位请求
        curPhoneNum = "";//当前老人的手机号码置为空

        // 构建Marker图标
        mBitmap = BitmapDescriptorFactory.fromResource(R.drawable.thumb);

        initWidget(view);

//        locationBaby();//定位孩子位置

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();

        if (mMapView != null)
            mMapView.onResume();

        tv_title.setText(sp.getString(Constant.CURRENTCHILDNAME, ""));

        if (handle != null)
            handle.removeCallbacksAndMessages(null);
        firstLoc = true;
        locationBaby();//定位孩子位置

    }

    /**
     * 定位孩子位置
     */
    private void locationBaby() {

        if (!CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {//当前有选中的孩子
            //先判断权限是否够

            if (Constant.POWER_ADMIN == sp.getInt(Constant.LEVEL, -1) || Constant.POWER_PARENT == sp.getInt(Constant.LEVEL, -1)) {

                getBabyLocation(LOCATION_TYPE_LOC);//loc模式定位

            } else {

                pageNoPermission();

                showToast(getResources().getString(R.string.have_no_right));

            }

        } else { //没有选择过孩子

            //获取所有孩子信息  和 权限
            getChildernAndWatch();

        }

    }

    /**
     * 没有权限的页面
     */
    private void pageNoPermission() {

        // 没有权限
        tv_add.setVisibility(View.INVISIBLE);//添加手表的按钮消失
        rl_no_baby.setVisibility(View.VISIBLE);
        iv_left.setVisibility(View.INVISIBLE);

    }

    /**
     * 有权限 有sn码  正常定位
     */
    private void pageWithPermissionAndSN() {

        rl_no_baby.setVisibility(View.GONE);
        iv_left.setVisibility(View.VISIBLE);

    }

    /**
     * 有权限但是没有sn码
     */
    private void pageWithPermissionNoSN() {

        rl_no_baby.setVisibility(View.VISIBLE);
        tv_add.setVisibility(View.VISIBLE);
        iv_left.setVisibility(View.INVISIBLE);

    }

    /**
     * 没有权限的页面
     */
    private void pageWithPermission() {

        rl_no_baby.setVisibility(View.GONE);
        iv_left.setVisibility(View.VISIBLE);

    }

    @Override
    public void onPause() {
        super.onPause();

        // 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (mMapView != null)
            mMapView.onPause();

    }

    @Override
    public void onDestroy() {

        if (mBaiduMap != null)
            mMapView.onDestroy();

        if (mLocClient != null)
            mLocClient.stop();

        //移除runnable
        if (handle != null) {
            handle.removeCallbacksAndMessages(null);
        }

        LogUtil.e("tag", "====== 定位fragment destory 销毁 =======");

        EventBus.getDefault().unregister(this);
//        mApplication.cancelPendingRequests(getClass().getName());

        super.onDestroy();
    }

    /**
     * 切换宝宝
     *
     * @param isChange 是否切换了宝宝
     */
    public void onEventMainThread(Boolean isChange) {

        LogUtil.e("tag", "是否切换了老人===== : " + isChange);

        if (isChange) {//切换了宝宝

            curPhoneNum = "";//当前老人的手机号码置为空
            noLocation();//清空当前显示的位置信息

            babyStuLat = 0;//定位信息 重置
            babyStuLng = 0;

            if (handle != null) {

                //移除所有的message 和 runnable
                handle.removeCallbacksAndMessages(null);

//                delay = 0;
                //第一次 loc 定位
                firstLoc = true;
                location_type = LOCATION_TYPE_LOC;
                handle.post(runnable);
//                handle.postDelayed(runnable, LOCATION_INTERVAL_TIME);
//                handle.postDelayed(gpsRun, LOCATION_INTERVAL_THITRY);

            }

        }

    }

    private Handler handle = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case LOCATION_MSG_CODE_TEN:

//                    //让地图定位到孩子位置
//                    if (moveTolocation(msg)) return;

                    if (handle != null) {
//                        handle.removeCallbacks(runnable);//先移除掉该runnanble
//                    handle.removeCallbacksAndMessages(null);
                        handle.postDelayed(runnable, LOCATION_INTERVAL_TIME);
                    }

                    break;

            }
        }
    };

    /**
     * 点击底部导航栏 重新定位
     */
    public void reBottonLocation() {

        LogUtil.e("tag", "   ==== 重新定位 ====   ");
        location_type = LOCATION_TYPE_LOC;
        getBabyLocation(location_type);

    }

    /**
     * //让地图定位到孩子位置
     *
     * @param childInfo
     * @return
     */
    private void moveTolocation(LocationBean.LocationChildInfo childInfo) {

        this.childInfo = childInfo;

        if (childInfo == null || childInfo.device == null) {
            return;
        }

        setBabyData(childInfo);

        if (mBaiduMap == null)
            return;

        try {

            mBaiduMap.clear();

            if (!CommonUtils.isNull(childInfo.device.stuLat) && !CommonUtils.isNull(childInfo.device.stuLng)) {

                MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(16.0f);
                mBaiduMap.setMapStatus(msu);

                babyStuLat = Double.parseDouble(childInfo.device.stuLat);
                babyStuLng = Double.parseDouble(childInfo.device.stuLng);
                location(babyStuLat, babyStuLng);
            } else {

                MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(12.0f);
                mBaiduMap.setMapStatus(msu);

//                LogUtil.e("tag", "我的坐标:" + mApplication.myLatitude + ",: " + mApplication.myLongitude);
                if (mApplication.myLatitude != 0 && mApplication.myLongitude != 0)
                    locationMy(mApplication.myLatitude, mApplication.myLongitude);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    /**
     * 定位到坐标点
     *
     * @param lat
     * @param lng
     */
    private void location(Double lat, Double lng) {

        if (!isAdded()) {//如果当前的fragment被销毁了
            if (handle != null)
                handle.removeCallbacksAndMessages(null);
            return;
        }

        try {
            if (mBitmap == null || mBaiduMap == null)
                return;
            mBaiduMap.clear();
            point = new LatLng(lat, lng);
            option = new MarkerOptions().position(point).icon(mBitmap).zIndex(5);
            marker = (Marker) (mBaiduMap.addOverlay(option));
            // 定位到该点
            u = MapStatusUpdateFactory.newLatLng(point);
            if (mBaiduMap != null)
                mBaiduMap.setMapStatus(u);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void locationMy(Double lat, Double lng) {

        if (!isAdded()) {//如果当前的fragment被销毁了
            if (handle != null)
                handle.removeCallbacksAndMessages(null);
            return;
        }
        try {
            if (mBitmap == null || mBaiduMap == null)
                return;

            mBaiduMap.clear();
            point = new LatLng(lat, lng);
            // 定位到该点
            u = MapStatusUpdateFactory.newLatLng(point);
            if (mBaiduMap != null)
                mBaiduMap.setMapStatus(u);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //GSM 定位
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {

//            LogUtil.e("tag", "请求一次  GSM  定位,该线程的名字:" + Thread.currentThread().getName());

//            LogUtil.e("tag", " 是否添加 : " + isAdded());

            if (!isAdded()) { //fragment 被销毁了
                if (handle != null)
                    handle.removeCallbacksAndMessages(null);
                return;
            }

            //获取宝宝的位置
            getBabyLocation(location_type);

        }
    };


    private void locationErr() {

        rl_no_baby.setVisibility(View.VISIBLE);
        iv_left.setVisibility(View.INVISIBLE);
        tv_add.setVisibility(View.INVISIBLE);

    }

//    //GPS 定位
//    private Runnable gpsRun = new Runnable() {
//        @Override
//        public void run() {
//
////            LogUtil.e("tag", "请求一次  GPS  定位,该线程的名字:" + Thread.currentThread().getName());
//
//            LogUtil.e("tag", " 是否添加 : " + isAdded());
//            if (!isAdded()) {//fragment 被销毁了
//                if (handle != null)
//                    handle.removeCallbacksAndMessages(null);
//                return;
//            }
//
//            //获取宝宝的位置
//            getBabyLocation(GPS);
//
//        }
//    };

    /**
     * 获取宝宝的位置 (真正定位接口)
     *
     * @param type 定位类型  gps or ""
     */
    private void getBabyLocation(final String type) {

        if (!CommonUtils.isNetworkAvailable(getActivity())) {
            reLocation();//重新定位孩子的位置
            LogUtil.e("tag", "  ===  网络不可用  === " );
            return; //网络不可用 直接返回
        }

        Log.e("tag", "   ===== 获取定位信息一次 =====   ");

        final JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("id", sp.getString(Constant.CURRENTCHILDID, ""));
        j.put("locationtype", type);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.WEB_ROOT + Constant.GETCHILDLOC, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {

                location_type = "";//把定位模式设置成 "" 模式

                if (LOCATION_TYPE_GPS.equals(type)) {//gps定位 无需操作, 只是请求而已
//                    LogUtil.e("tag", "==== gps 定位 ====");
                    return;
                }

                if (LOCATION_TYPE_LOC.equals(type)) {//如果是loc定位, 第一次loc定位定位孩子的位置,其余的不定位孩子的位置

//                    LogUtil.e("tag", "==== loc 定位 ====");

                    if (!firstLoc) { //如果不是第一次 loc模式的 定位  则不定位孩子位置

                        return;
                    } else { //如果是第一次定位, 修改值为false, 然后继续 定位孩子位置

                        firstLoc = false;
                    }

                }

                showLocation(response); //定位到孩子的位置

                reLocation();//重新定位孩子的位置

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                LogUtil.e("tag", "孩子定位信息fail");

                //孩子定位数据失败,30s后重新定位
                handle.postDelayed(runnable, LOCATION_INTERVAL_TIME);
            }

        }) {

            protected Map<String, String> getParams() {
                Map<String, String> param = new HashMap<String, String>();
                param.put("data", j.toJSONString());

                return param;
            }

        };

        //把请求加入队列
        mApplication.addToRequestQueue(stringRequest, getClass().getName());

    }

    /**
     * 定位老人位置
     *
     * @param response
     */
    private void showLocation(String response) {

        LogUtil.e("tag", "老人定位信息:" + response);

        try {

            LocationBean locationResutl = JSONObject.parseObject(response, LocationBean.class);

            if (locationResutl == null)  //没有位置信息,则不做处理, 让子线程继续请求
                return;

            if (Constant.STATUS_SUCCESS == locationResutl.code) {

                if (locationResutl.data == null || locationResutl.data.size() < 1) {

                    locationErr();
                    return;
                }

                //获取到该宝宝信息
                LocationBean.LocationChildInfo currentChild = locationResutl.data.get(0);

                if (currentChild == null || currentChild.device == null) { //防止出错

                    locationErr();

                    return;
                }

                //当前的手表电话号码
                curPhoneNum = currentChild.device.phoneNum;

                //先判断sn码是否存  再判断等级是否够
                if (!CommonUtils.isNull(currentChild.device.sn)) {

                    //管理员和亲人 并且有sn码   有权限
                    if (Constant.POWER_ADMIN == sp.getInt(Constant.LEVEL, 0) || Constant.POWER_PARENT == sp.getInt(Constant.LEVEL, 0)) {

                        pageWithPermission();

                    } else {

                        //朋友 没有权限
//                                showToast("权限等级不够,请联系管理员");
                        pageNoPermission();

                        return;
                    }

                } else {
                    //没有手表
//                            showToast("请给孩子绑定手表");
                    pageWithPermissionNoSN();
                    return;
                }

                //让地图定位到孩子位置
                moveTolocation(currentChild);

            } else {

                if (locationResutl.code == Constant.FA_PHNOEKEY_ERROR) {//如果是TOKEN 错误, 提示重新登录
                    showToast(Constant.showErrorMsg(locationResutl.code, getActivity()));
                    return;
                } else if (Constant.FA_RIGHT_ERROR == locationResutl.code) {
                    //没有权限
//                            showToast("权限等级不够,请联系孩子管理员");
                    pageNoPermission();

                }

                //请求数据失败
                locationErr();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 30秒后重新定位孩子的位置
     */
    private void reLocation() {
        //30秒定位
        Message msg = Message.obtain();
        msg.what = LOCATION_MSG_CODE_TEN;
        handle.sendMessage(msg);
    }

    private void initWidget(View view) {

        iv_left = (ImageView) view.findViewById(R.id.iv_left);
        ImageView iv_right = (ImageView) view.findViewById(R.id.iv_right);
        tv_title = (TextView) view.findViewById(R.id.tv_title);

        tv_title.setText(getResources().getString(R.string.location));

        ImageView iv_location = (ImageView) view.findViewById(R.id.iv_location);
        ImageView iv_call = (ImageView) view.findViewById(R.id.iv_call);
        ImageView iv_history = (ImageView) view.findViewById(R.id.iv_history);
//        ImageView iv_share = (ImageView) view.findViewById(R.id.iv_share);
        //广告页
        rl_no_baby = (RelativeLayout) view.findViewById(R.id.rl_no_baby);
        tv_add = (TextView) view.findViewById(R.id.tv_add);

        tv_add.setOnClickListener(this);
        //当前显示的孩子的信息
        tv_title_name = (TextView) view.findViewById(R.id.tv_title_name);
//        tv_time = (TextView) view.findViewById(R.id.tv_time);
        tv_child_location = (TextView) view.findViewById(R.id.tv_child_location);
        tv_watch_battery = (TextView) view.findViewById(R.id.tv_watch_battery);
        tv_location_type = (TextView) view.findViewById(R.id.tv_location_type);
        tv_status = (TextView) view.findViewById(R.id.tv_status);
        iv_status = (ImageView) view.findViewById(R.id.iv_status);
        mBatteryView = (BatteryView) view.findViewById(R.id.bv_battery);
        iv_location_type = (ImageView) view.findViewById(R.id.iv_location_type);

        // 地图初始化
        mMapView = (MapView) view.findViewById(R.id.bmapView);

        // 获取地图控件引用
        mBaiduMap = mMapView.getMap();

        //修改缩放比例  缩放级别为3~19，19为最近，3为最远
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(16.0f);
//        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(12.0f);
        mBaiduMap.setMapStatus(msu);

//        //去掉缩放按钮
//        removeZoomControl();

        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {

            @Override
            public boolean onMapPoiClick(MapPoi arg0) {
                return false;
            }

            @Override
            public void onMapClick(LatLng arg0) {
                if (mBaiduMap != null)
                    mBaiduMap.hideInfoWindow();
            }
        });

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker arg0) {

                showBabyLocationInfo(new LatLng(babyStuLat, babyStuLng));
//                LogUtil.e("tag", "======  OnMarkerClick  ======");
                return false;
            }

        });

//        mPopwindow.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View arg0) {
//                mBaiduMap.hideInfoWindow();
//            }
//        });

        getMyLocation();

        iv_left.setOnClickListener(this);
        iv_right.setOnClickListener(this);

        iv_location.setOnClickListener(this);
        iv_call.setOnClickListener(this);
        iv_history.setOnClickListener(this);
//        iv_share.setOnClickListener(this);

    }

//    /**
//     * 去掉缩放按钮
//     */
//    private void removeZoomControl() {
//        int count = mMapView.getChildCount();
//        for (int i = 0; i < count; i++) {
//            View child = mMapView.getChildAt(i);
//            // 隐藏百度logo ZoomControl
//            // if (child instanceof ImageView || child instanceof ZoomControls)
//            // {
//            if (child instanceof ZoomControls) {
//                child.setVisibility(View.INVISIBLE);
////                break;
//            }
//        }
//    }

    /**
     * 获取到我的当前位置
     */
    private void getMyLocation() { // 开启定位图层

        mBaiduMap.setMyLocationEnabled(true);
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_center_point_my);
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker));
//        //定位的点击事件
//        mBaiduMap.setOnMyLocationClickListener(new BaiduMap.OnMyLocationClickListener() {
//
//            @Override
//            public boolean onMyLocationClick() {
//
//                LatLng latLng = new LatLng(mApplication.myLatitude, mApplication.myLongitude);
//                showMyLocationInfo(latLng);
//                return false;
//            }
//        });

        mLocClient = new LocationClient(getActivity());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
//        option.setScanSpan(1000000);
        mLocClient.setLocOption(option);
        mLocClient.start();

    }

    @Override
    public void onClick(View view) {

        if (settingDialog != null && settingDialog.isShowing())
            settingDialog.dismiss();

        switch (view.getId()) {

            case R.id.iv_left://手表设置

                showSetting();

                break;
            case R.id.iv_right://切换宝宝

                mIntent = new Intent(getActivity(), ChooseLocationBabyActivity.class);
                startActivity(mIntent);

                break;
            case R.id.iv_location://定位 请求gps定位

                //定位到老人位置
                if (babyStuLat != 0 && babyStuLng != 0)
                    location(babyStuLat, babyStuLng);
                else {//如果没有老人的位置信息 则定位到 我 的位置
                    if (mApplication.myLatitude != 0 && mApplication.myLongitude != 0)
                        locationMy(mApplication.myLatitude, mApplication.myLongitude);
                }
//                getMyLocation();

                //调用接口 传递 gps 参数
                getBabyLocation(LOCATION_TYPE_GPS);

                break;

//            case R.id.iv_share://分享
//
//                if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {
//                    showToast(getResources().getString(R.string.please_choose_first));
//                    return;
//                }
//
//                //邀请码
//                mIntent = new Intent(getActivity(), InviteActivity.class);
////                mIntent.putExtra("childId", sp.getString(Constant.CURRENTCHILDID, ""));
//                startActivity(mIntent);
//
//                break;

            case R.id.tv_add://添加SN码

                mIntent = new Intent(getActivity(), SnCodeActivity.class);
                startActivity(mIntent);

                break;

            case R.id.iv_call://拨打电话

                if (CommonUtils.isNull(curPhoneNum)) {
                    showToast(getResources().getString(R.string.please_set_phone));
                    return;
                }

                if (curPhoneNum != null)

                    new AlertDialog.Builder(getActivity()).setMessage(curPhoneNum).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).setPositiveButton("呼叫", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            dialog.dismiss();

                            if (CommonUtils.isNull(curPhoneNum)) {
                                showToast("请给手表安装SIM卡,并在手表状态页面设置");
                                return;
                            }

                            //拨打电话
                            Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + curPhoneNum));
                            startActivity(intent);

                        }
                    }).show();

                break;
            case R.id.iv_history://历史轨迹

                mIntent = new Intent(getActivity(), HistoryActivity.class);
                startActivity(mIntent);
                break;

            case R.id.tv_safe_area://安全区域

                if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {
                    showToast(getResources().getString(R.string.please_bind_first));
                    return;
                }

                mIntent = new Intent(getActivity(), SafeAreaActivity.class);
//                mIntent.putExtra("id", currentShowBaby.id);
                startActivity(mIntent);
                break;

            case R.id.tv_white_list://手环白名单

                if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {
                    showToast(getResources().getString(R.string.please_bind_first));
                    return;
                }
                mIntent = new Intent(getActivity(), WhiteListActivity.class);
//                mIntent.putExtra("sn", currentShowBaby.sn);
//                mIntent.putExtra("watchId", currentShowBaby.id);
                startActivity(mIntent);

                break;
            case R.id.tv_state://手表设置

                if (childInfo == null) {
                    showToast(getResources().getString(R.string.please_bind_first));
                    return;
                }

                mIntent = new Intent(getActivity(), WatchStatusActivity.class);
                mIntent.putExtra("child", (Serializable) childInfo);
                startActivity(mIntent);

                break;
            case R.id.tv_unbind://解绑手表

                if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {
                    showToast(getResources().getString(R.string.please_bind_first));
                    return;
                }

                showUnwrapWatchDialog();
                break;

            case R.id.tv_find_watch://查找手表

                if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {
                    showToast(getResources().getString(R.string.please_bind_first));
                    return;
                }

                findWatch();

                break;
        }
    }

    /**
     * 查找手表, 手表响铃
     */
    private void findWatch() {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("id", sp.getString(Constant.CURRENTCHILDID, ""));
//        org.json.JSONObject j = new org.json.JSONObject();
//        j.put();

        HttpUtil.setPostRequest("准备中...", getActivity(), Constant.WEB_ROOT + Constant.FINDWATCH, j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {

            @Override
            public void setOnSuccessListener(String str) {

                try {
                    org.json.JSONObject result = new org.json.JSONObject(str);

                    if (Constant.STATUS_SUCCESS != result.getInt("code"))
                        Constant.showErrorMsg(result.getInt("code"), getActivity());

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, null);

    }


    /**
     * 手表设置
     */
    private void showSetting() {

        settingDialog = new ProgressDialog(getActivity());
        settingDialog.setCanceledOnTouchOutside(true);
        settingDialog.show();
        settingDialog.setContentView(R.layout.dialog_setting);

        TextView tv_safe_area = (TextView) settingDialog.findViewById(R.id.tv_safe_area);
        TextView tv_white_list = (TextView) settingDialog.findViewById(R.id.tv_white_list);
        TextView tv_state = (TextView) settingDialog.findViewById(R.id.tv_state);
        TextView tv_unbind = (TextView) settingDialog.findViewById(R.id.tv_unbind);
        TextView tv_find_watch = (TextView) settingDialog.findViewById(R.id.tv_find_watch);


        tv_safe_area.setOnClickListener(this);
        tv_white_list.setOnClickListener(this);
        tv_state.setOnClickListener(this);
        tv_unbind.setOnClickListener(this);
        tv_find_watch.setOnClickListener(this);

    }

    /**
     * 弹出提示解除绑定手表的对话框
     */
    private void showUnwrapWatchDialog() {

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setCanceledOnTouchOutside(true);
        progressDialog.show();
//        View view = View.inflate(getActivity(), R.layout.item_show_remind, null);
        progressDialog.setContentView(R.layout.item_show_remind);
        TextView tv_confirm = (TextView) progressDialog.findViewById(R.id.tv_confirm);
        TextView tv_cancel = (TextView) progressDialog.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }
        });

        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                unwrapWatch();

                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }

            }
        });

    }

    //解绑手表
    private void unwrapWatch() {

        JSONObject j = new JSONObject();
//        if (currentShowBaby != null)
        j.put("id", sp.getString(Constant.CURRENTCHILDID, ""));
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("解绑中...", getActivity(), Constant.WEB_ROOT + Constant.UNBINDWTACH, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            org.json.JSONObject result = new org.json.JSONObject(str);

                            if (result.getInt("code") == Constant.STATUS_SUCCESS) {
                                showToast("解绑成功");
                                getChildernAndWatch();
                            } else {
                                showToast(Constant.showErrorMsg(result.getInt("code"), getActivity()));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }
                }, null);
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
                return;
            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();

            mApplication.myLatitude = location.getLatitude();
            mApplication.myLongitude = location.getLongitude();

            mBaiduMap.setMyLocationData(locData);

        }

    }

    private TextView myLocatView;

//    /**
//     * 显示我的位置
//     *
//     * @param latLng
//     */
//    private void showMyLocationInfo(LatLng latLng) {
//
//        if (myLocatView == null) {
//            myLocatView = new TextView(getActivity());
//            myLocatView.setGravity(Gravity.CENTER);
//            myLocatView.setBackgroundResource(R.drawable.ic_mylocation_bg);
//        }
//        myLocatView.setText("我的位置");
//        InfoWindow myInfoWindow = new InfoWindow(myLocatView, latLng, 10);
//        mBaiduMap.showInfoWindow(myInfoWindow);
//
//    }

    /**
     * 显示我的位置
     *
     * @param latLng
     */
    private void showBabyLocationInfo(LatLng latLng) {

        if (myLocatView == null) {
            myLocatView = new TextView(getActivity());
            myLocatView.setGravity(Gravity.CENTER);
            myLocatView.setBackgroundResource(R.drawable.ic_mylocation_bg);
        }

        myLocatView.setText(babyName);
        myInfoWindow = new InfoWindow(myLocatView, latLng, -10);
        mBaiduMap.showInfoWindow(myInfoWindow);

    }

    private void getChildernAndWatch() {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("获取数据中...", getActivity(), Constant.WEB_ROOT + Constant.GETCHILDERNANDEWATCH,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {

                    @Override
                    public void setOnSuccessListener(String str) {
                        try {

                            ChildAndWatchInforResult result = JSONObject.parseObject(str, ChildAndWatchInforResult.class);

                            if (result.code == Constant.STATUS_SUCCESS) {

                                if (result.data == null) {

                                    locationErr();
                                    showToast(getResources().getString(R.string.no_bind_data));
                                    return;
                                }

                                if (result.data.size() > 0) {

                                    childList = result.data;

                                    if (childList == null) {
                                        showToast(getResources().getString(R.string.no_bind_data));
                                        locationErr();
                                        return;
                                    }

                                    Child currentShowBaby = childList.get(0);//默认选择第一个

                                    if (currentShowBaby == null) {
                                        locationErr();
                                        return;
                                    }

                                    //sp中存储默认的第一个
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString(Constant.CURRENTCHILDID, currentShowBaby.id);
                                    edit.putString(Constant.CURRENTCHILDNAME, currentShowBaby.name);
                                    edit.putInt(Constant.LEVEL, currentShowBaby.level);
                                    edit.apply();
                                    tv_title.setText(currentShowBaby.name);

                                    if (Constant.POWER_ADMIN == currentShowBaby.level || Constant.POWER_PARENT == currentShowBaby.level) {

                                        //先判断等级是否够  再判断sn码是否存在
                                        if (!CommonUtils.isNull(currentShowBaby.device.sn)) {
                                            //管理员和亲人 并且有sn码   有权限, 可以获取孩子的位置信息

                                            //请求孩子定位数据
                                            if (handle != null) {
                                              handle.post(runnable);
                                            }

                                        } else {
                                            //有权限 没有手表

                                            showToast(getResources().getString(R.string.please_bind_watch));
                                            pageWithPermissionNoSN();

                                            return;
                                        }

                                        //正常定位状态
                                        pageWithPermissionAndSN();

                                    } else {
                                        //朋友权限 没有权限
                                        showToast(getResources().getString(R.string.have_no_right));
                                        pageNoPermission();

                                    }

                                } else {

                                    //没有绑定过老人 (跳到绑定老人的页面)
                                    mIntent = new Intent(getActivity(), AddBabyActivity.class);
                                    mIntent.putExtra("cancle", false);
                                    startActivity(mIntent);
                                }

                            } else {
                                showToast(Constant.showErrorMsg(result.code, getActivity()));
                            }

                        } catch (Exception e) {
                            showToast(Constant.NODATA);
                            e.printStackTrace();
                        }
                    }
                }, null);
    }


    private void noLocation() {

        tv_title_name.setText("");

        mBatteryView.setPower(0);

        tv_location_type.setText("暂无定位");
        iv_location_type.setImageBitmap(null);

        tv_status.setText("");
        iv_status.setImageBitmap(null);
    }

    private void setBabyData(LocationBean.LocationChildInfo babyInfo) {

        babyName = babyInfo.name;
        tv_title_name.setText(CommonUtils.isNull(babyName) ? "" : babyName + "  " + AbDateUtil.getStringByFormat(babyInfo.device.updateTime, AbDateUtil.dateFormatYMDHMS));
        tv_title.setText(CommonUtils.isNull(babyName) ? "" : babyName);
//                        tv_time.setText(date.toLocaleString());

        tv_child_location.setText(CommonUtils.isNull(babyInfo.device.location) ? "" : babyInfo.device.location);
        if (!CommonUtils.isNull(babyInfo.device.battery)) {
            tv_watch_battery.setText(babyInfo.device.battery + "%");
            int currentBattery = Integer.parseInt(babyInfo.device.battery);
            if (currentBattery <= 20) {//电量小于20变红
                mBatteryView.setLength(35, 15, 5, 10, 1);
                mBatteryView.setColor(Color.BLACK, Color.RED);

            } else { //大于20是绿的

                mBatteryView.setLength(35, 15, 5, 10, 1);
                mBatteryView.setColor(Color.BLACK, Color.GREEN);
            }

            if (currentBattery <= 5) {
                mBatteryView.setPower(5);
            } else {
                mBatteryView.setPower(currentBattery);
            }

        }

        if ("gsm".equals(babyInfo.device.provider)) {//基站定位

            tv_location_type.setText("基站定位");
            iv_location_type.setImageResource(R.drawable.location_station);

        } else if ("gps".equals(babyInfo.device.provider)) {//gps定位

            tv_location_type.setText("GPS定位");
            iv_location_type.setImageResource(R.drawable.location_gps);

        } else if ("wifi".equals(babyInfo.device.provider)) {//wifi定位

            tv_location_type.setText("wifi定位");
            iv_location_type.setImageResource(R.drawable.location_wifi);
        } else {
            tv_location_type.setText("暂无定位");
        }


        if (babyInfo.device.gsm == 0) {
            iv_status.setImageResource(R.drawable.signal_zero);
        } else if (babyInfo.device.gsm <= 20) {
            iv_status.setImageResource(R.drawable.signal_twenty);
        } else if (babyInfo.device.gsm <= 40) {
            iv_status.setImageResource(R.drawable.signal_fourty);
        } else if (babyInfo.device.gsm <= 60) {
            iv_status.setImageResource(R.drawable.signal_sixty);
        } else if (babyInfo.device.gsm <= 99) {
            iv_status.setImageResource(R.drawable.signal_eighty);
        } else if (babyInfo.device.gsm == 100) {
            iv_status.setImageResource(R.drawable.signal_full);
        }

        tv_status.setText(babyInfo.device.online ? "在线" : "离线");

    }


}